#pragma once
#include <iostream>
#include <string>
#include <pthread.h>
#include <functional>


namespace ThreadMoudle
{
    // typedef void(*func_t)(const std::string &name);
    using func_t = std::function<void(const std::string &name)>;
    class Thread
    {
    public:
        void Excute()
        {
            std::cout << _name << " is running" << std::endl;
            _isrunning = true;
            _func(_name);
            _isrunning = false;
        }
    private:
        std::string _name;
        pthread_t _tid;
        bool _isrunning;
        func_t _func;

    public:
        Thread(const std::string name, func_t func) : _name(name), _func(func)
        {
            std::cout << "create " << name << " done" << std::endl;
        }

        // 该方法属于类，不属于对象，参数没有this指针
        static void* ThreadRoutine(void* args)
        {
            Thread* self = static_cast<Thread*>(args); // 获得当前对象
            self->Excute();
            return nullptr;
        }

        bool Start()
        {
            int n = ::pthread_create(&_tid, nullptr, ThreadRoutine, this);
            if(n != 0)  return false;

            return true;
        }

        std::string Status()
        {
            if(_isrunning) return "running";
            return "sleep";
        }

        void Stop()
        {
            if(_isrunning)
            {
                pthread_cancel(_tid);
                _isrunning = false;
                std::cout << _name << " stop" << std::endl;
            }
        }

        void Join()
        {
            ::pthread_join(_tid, nullptr);
            std::cout << _name << " joined" << std::endl;
        }

        std::string Name()
        {
            return _name;
        }

        ~Thread()
        {
            
        }
    };

    
};